<?php


namespace app\api\controller\ShopGoods;


use app\api\controller\AppController;
use app\api\model\Order\OrderGoodsModel;
use app\api\model\Order\OrderModel;
use app\api\model\ShopGoods\ShopGoodsAttrModel;
use app\api\model\ShopGoods\ShopGoodsAttrValueModel;
use app\api\model\ShopGoods\ShopGoodsModel;
use app\api\model\User\UserAddressModel;
use app\api\model\User\UserWalletModel;
use app\Request;
use app\Utils\ImageUtil;
use app\Utils\StrUtil;
use app\Utils\Util;
use Exception;
use think\facade\Db;

class ShopGoodsOrder extends AppController
{

    /**
     * @api {post} /per_shop_order_info 获取预创建订单信息
     * @apiGroup 积分商城
     * @apiParam {string} token Token
     * @apiParam {array} list 商品集合
     * @apiParam {int} list[][goods_id] 商品ID
     * @apiParam {int} list[][number] 数量
     * @apiParam {string} list[][unique] 属性unique
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function preShopOrderInfo(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        if(empty($user)){
            return Util::returnJson(self::CODE_LOGIN,null,"请登录");
        }
        if(empty($param['list']) && empty($param['list'])){
            return Util::returnJson(self::CODE_ERROR,null,"参数错误5");
        }
        //最终总价格
        $total_all_price = 0;
        //最终总消耗积分
        $total_all_integral = 0;
        //总数量
        $number = 0;
        //总抵扣
        $all_deduction_price = 0;
        //总邮费
        $all_postage = 0;

        //商品列表
        $list = [];
        foreach ($param['list'] as $item){
            if(empty($item['goods_id']) && empty($item['goods_id'])){
                return Util::returnJson(self::CODE_ERROR,null,"参数错误6");
            }
            if(empty($item['number']) && empty($item['number'])){
                return Util::returnJson(self::CODE_ERROR,null,"请选择商品数量");
            }
            $goodsInfo = ShopGoodsModel::getGoodsWhere(['id'=>$item['goods_id'],'is_show'=>1,'is_del'=>0]);

            if(empty($goodsInfo)){
                return Util::returnJson(self::CODE_ERROR,null,"商品不存在或已下架");
            }else{
                if(!empty($item['unique'])){
                    $attr_value = ShopGoodsAttrValueModel::getGoodsAttrValueWhere(['unique' => $item['unique']]);
                    if(!$attr_value) {
                        return Util::returnJson(self::CODE_ERROR,null,"商品".$goodsInfo['good_name']."规格不存在或已下架");
                    }
                    if ($attr_value['stock'] < $item['number']) {
                        return Util::returnJson(self::CODE_ERROR,null,"商品".$goodsInfo['good_name']."规格库存不足，无法购买");
                    }
                }else{
                    $attr = ShopGoodsAttrModel::getGoodsAttrWhereMore([['goods_id','=',$item['goods_id']]]);
                    if(!empty($attr)){
                        return Util::returnJson(self::CODE_ERROR,null,"请选择商品".$goodsInfo['good_name']."的规格");
                    }
                    if ($goodsInfo['stock'] < $item['number']) {
                        return Util::returnJson(self::CODE_ERROR,null,"商品".$goodsInfo['good_name']."库存不足，无法购买");
                    }
                    $attr_value = [
                        'integral'=>$goodsInfo['integral'],
                        'price'=>$goodsInfo['price'],
                        'vip_price'=>$goodsInfo['vip_price'],
                        'suk'=>$goodsInfo['good_name']
                    ];
                }
            }

            $price = 0;
            //价格
            if(!empty($user['level_id']) && (!empty($user['is_level_type']) || strtotime($user['end_time']) > time() )){
                //VIP
                $price = $attr_value['vip_price'];
            }else{
                $price = $attr_value['price'];
            }

            //总价格
            $total_price = $price*$item['number'];
            //总积分
            $total_integral = $attr_value['integral']*$item['number'];
            //邮费
            $postage = 0;
            //总邮费
            if(empty($goodsInfo['is_postage'])){
                $postage = $goodsInfo['postage'];
            }
            $all_postage += $postage;
            $number += $item['number'];
            $total_all_price += $total_price;
            $total_all_integral += $total_integral;
            $goodsInfo['img'] = ImageUtil::i()->replaceUrl($goodsInfo['img']);
            $goods_remarks = [
                "type"            => 1,
                "goods_id"        => $goodsInfo['id'],
                "unique"          => !empty($item['unique']) ? $item['unique'] : "",
                "total_price"     => $total_price,
                "total_integral"  => $total_integral,
                'is_postage'      => $goodsInfo['is_postage'],
                'postage'         => $postage,
                "deduction_price" => !empty($deduction_price) ? $deduction_price : 0,
                "number"          => $item['number'],
                "goods_price"     => $price,
                "suk"             => $attr_value['suk'],
                "goods_info"      => $goodsInfo
            ];
            array_push($list,$goods_remarks);
        }

        //验证积分是否充足
        $user_wallet = UserWalletModel::getUserWalletWhere(['uid'=>$user['id']]);
        if($user_wallet['integral'] < $total_all_integral || empty($user_wallet)){
            return Util::returnJson(self::CODE_ERROR,null,"用户积分不足");
        }

        $data = [
            'token'           => $param['token'],
            'list'            => $list,
            'count'           => count($list),
            'number'          => $number,
            'total_price'     => bcadd($total_all_price,$all_postage,2),
            'total_integral'  => $total_all_integral,
            'postage'         => $all_postage,
            'deduction_price' => !empty($all_deduction_price) ? $all_deduction_price : 0,
        ];

        //获取默认地址
        $address_list = UserAddressModel::getUserAddressWhereMore(['uid' => $user['id']]);
        if(!empty($address_list)){
            $address = [];
            foreach ($address_list as $item){
                if($item['is_default'] == 1){
                    $address = $item;
                }
            }
            if(!empty($address)){
                $data['address'] = $address;
            }else{
                $data['address'] = $address_list[0];
            }
        }else{
            $data['address'] = [];
        }
        return Util::returnJson(self::CODE_SUCCESS, $data, "");
    }

    /**
     * @api {post} /create_shop_goods_order 商品支付
     * @apiGroup 积分商城
     * @apiParam {string} token Token
     * @apiParam {int} source_type 来源 1:APP 2:微信公众号 3:小程序
     * @apiParam {int} pay_way 支付方式 1：余额  2:支付宝 3：微信
     * @apiParam {int} address_id 收货地址ID
     * @apiParam {array} list 商品集合
     * @apiParam {int} list[][goods_id] 商品ID
     * @apiParam {int} list[][number] 数量
     * @apiParam {string} list[][unique] 属性unique
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function createShopGoodsOrder(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        if(empty($user)){
            return Util::returnJson(self::CODE_LOGIN,null,"请登录");
        }
        //1:APP 2:微信公众号 3:小程序
        if (in_array($param['source_type'],[1,2,3])) {
            return Util::returnJson(self::CODE_ERROR,null,"来源错误");
        }
        if (in_array($param['pay_way'],[1,2,3])) {
            return Util::returnJson(self::CODE_ERROR,null,"支付类型错误");
        }

        $address = UserAddressModel::getUserAddressWhere(['id'=>$param['address_id']]);
        if(empty($address)){
            return Util::returnJson(self::CODE_ERROR,null,"请选择收获地址");
        }

        if(empty($param['list']) && empty($param['list'])){
            return Util::returnJson(self::CODE_ERROR,null,"参数错误5");
        }
        //最终总价格
        $total_all_price = 0;
        //最终总消耗积分
        $total_all_integral = 0;
        //总数量
        $number = 0;
        //总抵扣
        $all_deduction_price = 0;
        //总邮费
        $all_postage = 0;

        //商品列表
        $list = [];
        foreach ($param['list'] as $item){
            if(empty($item['goods_id']) && empty($item['goods_id'])){
                return Util::returnJson(self::CODE_ERROR,null,"参数错误6");
            }
            if(empty($item['number']) && empty($item['number'])){
                return Util::returnJson(self::CODE_ERROR,null,"请选择商品数量");
            }
            $goodsInfo = ShopGoodsModel::getGoodsWhere(['id'=>$item['goods_id'],'is_show'=>1,'is_del'=>0]);

            if(empty($goodsInfo)){
                return Util::returnJson(self::CODE_ERROR,null,"商品不存在或已下架");
            }else{
                if(!empty($item['unique'])){
                    $attr_value = ShopGoodsAttrValueModel::getGoodsAttrValueWhere(['unique' => $item['unique']]);
                    if(!$attr_value) {
                        return Util::returnJson(self::CODE_ERROR,null,"商品".$goodsInfo['good_name']."规格不存在或已下架");
                    }
                    if ($attr_value['stock'] < $item['number']) {
                        return Util::returnJson(self::CODE_ERROR,null,"商品".$goodsInfo['good_name']."规格库存不足，无法购买");
                    }
                }else{
                    $attr = ShopGoodsAttrModel::getGoodsAttrWhereMore([['goods_id','=',$item['goods_id']]]);
                    if(!empty($attr)){
                        return Util::returnJson(self::CODE_ERROR,null,"请选择商品".$goodsInfo['good_name']."的规格");
                    }
                    if ($goodsInfo['stock'] < $item['number']) {
                        return Util::returnJson(self::CODE_ERROR,null,"商品".$goodsInfo['good_name']."库存不足，无法购买");
                    }
                    $attr_value = [
                        'integral'  => $goodsInfo['integral'],
                        'price'     => $goodsInfo['price'],
                        'vip_price' => $goodsInfo['vip_price'],
                        'suk'       => $goodsInfo['good_name']
                    ];
                }
            }

            $price = 0;
            //价格
            if(!empty($user['level_id']) && (!empty($user['is_level_type']) || strtotime($user['end_time']) > time() )){
                //VIP
                $price = $attr_value['vip_price'];
            }else{
                $price = $attr_value['price'];
            }
            //总价
            $total_price = $price*$item['number'];
            //总积分
            $total_integral = $attr_value['integral']*$item['number'];
            //邮费
            $postage = 0;
            //总邮费
            if(empty($goodsInfo['is_postage'])){
                $postage = $goodsInfo['postage'];
            }
            $all_postage += $postage;

            $number += $item['number'];
            $total_all_price += $total_price;
            $total_all_integral += $total_integral;
            $goodsInfo['img'] = ImageUtil::i()->replaceUrl($goodsInfo['img']);
            $goods_remarks = [
                "type"            => 1,
                "goods_id"        => $goodsInfo['id'],
                "unique"          => !empty($item['unique']) ? $item['unique'] : "",
                "total_price"     => $total_price,
                "total_integral"  => $total_integral,
                'is_postage'      => $goodsInfo['is_postage'],
                'postage'         => $postage,
                "deduction_price" => !empty($deduction_price) ? $deduction_price : 0,
                "number"          => $item['number'],
                "goods_price"     => $price,
                "suk"             => $attr_value['suk'],
                "goods_info"      => $goodsInfo
            ];
            array_push($list,$goods_remarks);
        }

        //验证积分是否充足
        $user_wallet = UserWalletModel::getUserWalletWhere(['uid'=>$user['id']]);
        if($user_wallet['integral'] < $total_all_integral || empty($user_wallet)){
            return Util::returnJson(self::CODE_ERROR,null,"用户积分不足");
        }

        Db::startTrans();
        try {
            //商户订单号
            $out_trade_no = StrUtil::i()->getOrderSn(3);
            //商品订单号
            $order_sn = StrUtil::i()->getOrderSn();
            $data = [
                'order_sn'        => $order_sn,
                'uid'             => $user['id'],
                'type'            => 1,
                'total_price'     => bcadd($total_all_price,$all_postage,2),
                'total_integral'  => $total_all_integral,
                'postage'         => $all_postage,
                "deduction_price" => !empty($all_deduction_price) ? $all_deduction_price : 0,
                'username'        => $address['username'],
                'mobile'          => $address['mobile'],
                'address_details' => $address['region'].$address['detailed'],
                'up_time'         => date('Y-m-d H:i:s', time()),
                'add_time'        => date('Y-m-d H:i:s', time()),
                'mer_id'          => $goodsInfo['mer_id'],
                'ratio'           => $goodsInfo['merchant_ratio'],
                'pay_way'         => $param['pay_way'],
                'source_type'     => $param['source_type'],
                'pay_num'         => $number,
                'is_discounts'    => !empty($param['is_discounts']) ? 1 : 0,
            ];
            $order_id = OrderModel::addOrder($data);
            if (!empty($order_id)) {
                foreach ($list as &$order_goods){
                    $order_goods['goods_info']  = json_encode($order_goods['goods_info']);
                    $order_goods['order_id']    = $order_id;
                    $order_goods['up_time']     = date("Y-m-d H:i:s", time());
                    $order_goods['add_time']    = date("Y-m-d H:i:s", time());
                    //添加订单商品
                    $flag = OrderGoodsModel::addOrderGoods($order_goods);
                    if (!$flag) {
                        Db::rollback();
                        return Util::returnJson(self::CODE_ERROR,null,"订单创建失败");
                    }
                }
                //扣除积分
                UserWalletModel::integralOut($user['id'],$data['total_integral'],StrUtil::INTEGRAL_BILL_USE_TYPE['BUY_GOODS_USE'],"积分商城消耗");

                //判断支付金额是否调起支付
                if(!empty($data['total_price']) && $data['total_price'] > 0){
                    //调起支付
                    if($param['pay_way'] == 1 && $param['source_type'] == 1){
                        $result = $this->weChatPay("APP",$data['total_price'], $out_trade_no, "商品支付");
                    }else if($param['pay_way'] == 1 && ($param['source_type'] == 2 || $param['source_type'] == 3)){
                        $result = $this->weChatPay("JSAPI",$data['total_price'], $out_trade_no, "商品支付");
                    }else if($param['pay_way'] == 2){
                        $result = $this->weChatPay("YE",$data['total_price'], $out_trade_no, "商品支付");
                    }
                    if ($result['code'] == 0) {
                        //提交保存
                        Db::commit();
                        return Util::returnJson(self::CODE_SUCCESS,$result['data'],"下单成功");
                    } else {
                        Db::rollback();
                        return Util::returnJson(self::CODE_ERROR,null,$result['msg']);
                    }
                }else{
                    //直接付款成功
                    $save = [
                        'status'  => 1,
                        'up_time' => date("Y-m-d H:i:s",time())
                    ];
                    OrderModel::updateOrderWhere([['id','=',$order_id]],$save);
                    Db::commit();
                    return Util::returnJson(self::CODE_SUCCESS,$order_id,"付款成功");
                }
            } else {
                Db::rollback();
                return Util::returnJson(self::CODE_ERROR,null,"订单创建失败");
            }
        } catch (Exception $e) {
            Db::rollback();
            return Util::returnJson(self::CODE_ERROR,null,"下单失败！");
        }
    }

}